package com.juzhi.dvrapp;

import android.content.Context;
import android.os.Looper;
import android.util.Log;

import com.juzhi.dvrapp.manager.AppManager;
import com.juzhi.dvrapp.utils.FileUtils;
import com.juzhi.dvrapp.utils.T;

import java.io.File;
import java.io.FileWriter;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.lang.Thread.UncaughtExceptionHandler;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;


public class CrashHandler implements UncaughtExceptionHandler {

    private Context mContext;
    private UncaughtExceptionHandler mDefaultHandler;
    private static final SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd");
    private static CrashHandler INSTANCE = new CrashHandler();

    public static CrashHandler getInstance() {
        return INSTANCE;
    }

    public void init(Context ctx) {
        mContext = ctx;
        mDefaultHandler = Thread.getDefaultUncaughtExceptionHandler();
        Thread.setDefaultUncaughtExceptionHandler(this);
    }

    @Override
    public void uncaughtException(Thread thread, Throwable ex) {
        if (!handleException(ex) && mDefaultHandler != null) {
            //如果用户没有处理则让系统默认的异常处理器来处理
            mDefaultHandler.uncaughtException(thread, ex);
        } else {
            //Sleep一会后结束程序
            try {
                Thread.sleep(1000);  //睡眠3秒  是用于上传异常信息文件至服务器
                AppManager.getAppManager().AppExit(mContext);
            } catch (InterruptedException e) {
                Log.e("TAG", "Error : ", e);
            }
        }
    }

    /**
     * 自定义错误处理,收集错误信息 发送错误报告等操作均在此完成.
     *
     * @param ex
     * @return true:如果处理了该异常信息;否则返回false.
     */
    private boolean handleException(Throwable ex) {
        if (ex == null) {
            return false;
        }
        ex.printStackTrace();
        new Thread() {
            @Override
            public void run() {
                Looper.prepare();
                T.showShort(mContext.getResources().getString(R.string.string_app_error));
                Looper.loop();
            }
        }.start();
        // 保存日志文件
        saveCrashInfo2File(ex);
        return true;
    }

    private void saveCrashInfo2File(Throwable ex)
    {
        if(FileUtils.isSDCardMounted())
        {
            try
            {
                StringBuilder sb = new StringBuilder();
                StringWriter wr = new StringWriter();
                PrintWriter pw = new PrintWriter(wr);
                ex.printStackTrace(pw);
                String errorlog = wr.toString();
                sb.append(new Date());
                sb.append("\n");
                sb.append(errorlog);
                sb.append("\n");
                String log = sb.toString();
                File file = new File(FileUtils.LOG_PATH, sdf1.format(Calendar.getInstance().getTime())+"-bug.txt");
                if (!file.exists())
                    file.createNewFile();

                FileWriter writer = new FileWriter(file, true);
                writer.write(log);
                writer.flush();
                writer.close();
            }
            catch (Exception e)
            {

            }
        }
    }

}